package xhttp

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"

	"gitee.com/fun-pal/gopkg/xerror"
)

const (
	successCode = 0
	failedCode  = 1000
	successMsg  = "Success"
)

type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func JsonResponse(w http.ResponseWriter, v interface{}) {
	var resp = &Response{Data: make(map[string]interface{})}

	switch data := v.(type) {
	case *xerror.CustomError:
		resp.Code = data.Code
		resp.Msg = data.Msg
	case error:
		resp.Code = failedCode
		resp.Msg = data.Error()
	default:
		resp.Code = successCode
		resp.Msg = successMsg
		if resp.Data == nil {
			resp.Data = make(map[string]interface{})
		} else {
			resp.Data = data
		}
	}
	httpx.OkJson(w, resp)
}
